package com.yswee.framework.utils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import com.yswee.framework.Application;
import com.yswee.framework.R;
import com.yswee.framework.activity.IActivityContext;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Build;
import android.os.IBinder;
import androidx.core.app.NotificationCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;

public class OSUtils {

    private static LinearLayout mPopupView = null;

	/**
	 * 是否运行在前台
	 */
	public static boolean isRunningForeground() {
		Context context = Application.get();
		ActivityManager am = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		@SuppressWarnings("deprecation")
		ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
		String currentPackageName = cn.getPackageName();
		if (!TextUtils.isEmpty(currentPackageName)
				&& currentPackageName.equals(context.getPackageName())) {
			return true;
		}

		return false;
	}
	
	/**
	 * 切换至前台
	 * @return
	 */
	public static boolean moveTaskToFront(Class<?> mainActivity) {
		try {
			IActivityContext activity = com.yswee.framework.manager.ActivityManager.get().currentActivity();
			if(activity != null) {
				ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
				am.moveTaskToFront(activity.getTaskId(), 0);
				return true;
			} else {
				Intent intent = new Intent(Application.get(), mainActivity);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				Application.get().startActivity(intent);
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public static boolean isTranslucentOrFloating(Activity activity) {
        boolean isTranslucentOrFloating = false;
        try {
            int [] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
            final TypedArray ta = activity.obtainStyledAttributes(styleableRes);
            Method m = ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
            m.setAccessible(true);
            isTranslucentOrFloating = Boolean.parseBoolean(m.invoke(null, ta).toString());
            m.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isTranslucentOrFloating;
    }

	public static void hideNavigationBar(Activity context) {
		int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
				| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
				| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
				| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
				| View.SYSTEM_UI_FLAG_FULLSCREEN; // hide status bar
		if (android.os.Build.VERSION.SDK_INT >= 19) {
			uiFlags |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
		} else {
			uiFlags |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
		}
		try {
			context.getWindow().getDecorView().setSystemUiVisibility(uiFlags);
		} catch (Exception e) {

		}
	}
	
	public static boolean fixOrientation(Activity activity) {
        try {
            Field field = Activity.class.getDeclaredField("mActivityInfo");
            field.setAccessible(true);
            ActivityInfo o = (ActivityInfo)field.get(activity);
            o.screenOrientation = -1;
            field.setAccessible(false);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
	
	public static void closeAndroidPDialog(){
        try {
            Class<?> aClass = Class.forName("android.content.pm.PackageParser$Package");
            Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(String.class);
            declaredConstructor.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Class<?> cls = Class.forName("android.app.ActivityThread");
            Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
            declaredMethod.setAccessible(true);
            Object activityThread = declaredMethod.invoke(null);
            Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
            mHiddenApiWarningShown.setAccessible(true);
            mHiddenApiWarningShown.setBoolean(activityThread, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

	/**
	 * 获取app最大可用内存
	 */
	public static long getMaxMemory() {
		return Runtime.getRuntime().maxMemory();
	}
	
	public static Notification getForegroundNotification(Intent intent) {
		Context context = Application.get();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = context.getPackageName();
            String channelName = "消息通知";
            int channelImportance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel(channelId , channelName, channelImportance);
            channel.enableLights(true);
            channel.setShowBadge(true);
    		NotificationManager nm = (NotificationManager) context.
    				getSystemService(Context.NOTIFICATION_SERVICE);  
            nm.createNotificationChannel(channel);
            
            Notification.Builder nb = new Notification.Builder(context, channelId);
    		PendingIntent contentIntent = PendingIntent.getBroadcast(context, 0,
    				intent, PendingIntent.FLAG_UPDATE_CURRENT);
    		nb.setOngoing(true);
    		nb.setContentTitle(context.getString(R.string.app_name) + "为您服务");
    		nb.setSmallIcon(R.drawable.app_icon);
    		nb.setContentIntent(contentIntent);
			return nb.build();
		} else {
			NotificationCompat.Builder nb = new NotificationCompat.Builder(context);
			PendingIntent contentIntent = PendingIntent.getBroadcast(context, 0,
					intent, PendingIntent.FLAG_UPDATE_CURRENT);
			nb.setOngoing(true);
			nb.setContentTitle(context.getString(R.string.app_name) + "为您服务");
			nb.setSmallIcon(R.drawable.app_icon);
			nb.setContentIntent(contentIntent);
			return nb.build();
		}
	}
	
	@SuppressWarnings("deprecation")
	public static void showPopupWindow() {
    	try {
	        if (mPopupView != null) {
	            return;
	        }
	        // 获取应用的Context
	        Context context = Application.get();
	        // 获取WindowManager
	        WindowManager manager = (WindowManager) context
	                .getSystemService(Context.WINDOW_SERVICE);
	        // 创建view
	        mPopupView = new LinearLayout(context);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(10, 10);
			lp.gravity = Gravity.CENTER;
			mPopupView.setBackgroundColor(0x01FF0000);
			mPopupView.setLayoutParams(lp);
			Button btn = new Button(context);
			btn.setLayoutParams(lp);
			btn.setBackgroundColor(Color.TRANSPARENT);
			mPopupView.addView(btn);
			// 设置view
	        final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
	        params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
	        // 设置flag
	        // FLAG_NOT_TOUCH_MODAL不阻塞事件传递到后面的窗口
	        // 设置 FLAG_NOT_FOCUSABLE 悬浮窗口较小时，后面的应用图标由不可长按变为可长按
	        // 不设置这个flag的话，home页的划屏会有问题
	        int flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL|WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
	        // | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
	        // 如果设置了WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE，弹出的View收不到Back键的事件
	        params.flags = flags;
	        // 不设置这个弹出框的透明遮罩显示为黑色
	        params.format = PixelFormat.TRANSLUCENT;
	        params.width = LayoutParams.WRAP_CONTENT;
	        params.height = LayoutParams.WRAP_CONTENT;
	        params.gravity = Gravity.TOP|Gravity.LEFT;
	        manager.addView(mPopupView, params);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    
    /**
     * 底部虚拟按键栏的高度
     * @return
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static int getSoftButtonsBarHeight(WindowManager windowmanager) {
        DisplayMetrics metrics = new DisplayMetrics();
        //这个方法获取可能不是真实屏幕的高度
        windowmanager.getDefaultDisplay().getMetrics(metrics);
        int usableHeight = metrics.heightPixels;
        //获取当前屏幕的真实高度
        windowmanager.getDefaultDisplay().getRealMetrics(metrics);
        int realHeight = metrics.heightPixels;
        if (realHeight > usableHeight) {
            return realHeight - usableHeight;
        } else {
            return 0;
        }
    }
    
    /**
	 * 软键盘是否显示
	 * @param context
	 * @param view
	 */
	public static boolean isSoftInputShow(Dialog dialog) {
		try {
			DisplayMetrics metric = new DisplayMetrics();
			android.view.WindowManager wm = (android.view.WindowManager) Application.get().
					getSystemService(Context.WINDOW_SERVICE);
			wm.getDefaultDisplay().getMetrics(metric);
	        int screenheight = metric.heightPixels;
	        int viewheight = dialog.getWindow().getDecorView().getRootView().getHeight();
	        return isSoftInputShow(dialog.getWindow(), screenheight, viewheight);
		} catch (Exception e) { 
			return false;
		}
	}
    
    /**
	 * 软键盘是否显示
	 * @param context
	 * @param view
	 */
	public static boolean isSoftInputShow(Activity activity) {
		try {
	        Rect r = new Rect();
	        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
	        int screenheight = activity.getWindow().getDecorView().getRootView().getHeight();
	        int viewheight = r.bottom - r.top;
	        return isSoftInputShow(activity.getWindow(), screenheight, viewheight);
		} catch (Exception e) { 
			return false;
		}
	}
    
    /**
	 * 软键盘是否显示
	 * @param context
	 * @param view
	 */
	public static boolean isSoftInputShow(Window window, int screenHeight, int viewheight) {
		try {
	        //计算软件盘的高度
	        int softInputHeight = screenHeight - viewheight;
	        /**
	         * 某些Android版本下，没有显示软键盘时减出来的高度总是144，而不是零，
	         * 这是因为高度是包括了虚拟按键栏的(例如华为系列)，所以在API Level高于20时，
	         * 我们需要减去底部虚拟按键栏的高度（如果有的话）
	         */
	        if (Build.VERSION.SDK_INT >= 20) {
	            // When SDK Level >= 20 (Android L), the softInputHeight will contain the height of softButtonsBar (if has)
	            softInputHeight = softInputHeight - getSoftButtonsBarHeight(window.getWindowManager());
	        }
	        return softInputHeight > 0;
		} catch (Exception e) { 
			return false;
		}
	}
	
    /**
	 * 弹出软键盘
	 * @param context
	 * @param view
	 */
	public static void ShowSoftInput(Context context, View view){
		try {
			view.requestFocus();
			InputMethodManager imm = (InputMethodManager)context.getApplicationContext().
				getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
		} catch (Exception e) { }
	}
	
	/**
	 * 隐藏软键盘
	 * @param context
	 */
	public static void hideSoftInput(Context context){
		try {
			if(context instanceof Activity) {
				hideSoftInput(((Activity) context).getCurrentFocus().getWindowToken());
			}
		} catch (Exception e) { }
	}
	
	/**
	 * 隐藏软键盘
	 * @param context
	 */
	public static void hideSoftInput(Dialog dialog){
		try {
			hideSoftInput(dialog.getCurrentFocus().getWindowToken());
		} catch (Exception e) { }
	}
	
	/**
	 * 隐藏软键盘
	 * @param context
	 * @param activity
	 */
	public static void hideSoftInput(IBinder windowToken){
		try {
			InputMethodManager imm = (InputMethodManager)Application.get().
				getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(windowToken, InputMethodManager.HIDE_NOT_ALWAYS);
		} catch (Exception e) { }
	}
	
	/**
	 * Android 2.0
	 * @return
	 */
	public static boolean hasECLAIR() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR;
	}
	
	/**
	 * Android 2.0.1
	 * @return
	 */
	public static boolean hasECLAIR01() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_0_1;
	}
	
	/**
	 * Android 2.1.x
	 * @return
	 */
	public static boolean hasEclairMr1() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR_MR1;
	}
	
	/**
	 * Android 2.2.x
	 * @return
	 */
	public static boolean hasFroyo() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
	}

	/**
	 * Android 2.3
	 * Android 2.3.1
	 * Android 2.3.2
	 * @return
	 */
	public static boolean hasGingerbread() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
	}

	/**
	 * Android 2.3.3
	 * Android 2.3.4
	 * @return
	 */
	public static boolean hasGingerbreadMR1() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1;
	}

	/**
	 * Android 3.0.x
	 * @return
	 */
	public static boolean hasHoneycomb() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
	}


	/**
	 * Android 3.1.x
	 * @return
	 */
	public static boolean hasHoneycombMR1() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
	}


	/**
	 * Android 3.2
	 * @return
	 */
	public static boolean hasHoneycombMR2() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2;
	}


	/**
	 * Android 4.0
	 * Android 4.0.1
	 * Android 4.0.2
	 * @return
	 */
	public static boolean hasIcecreamSandwich(){
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
	}


	/**
	 * Android 4.0.3
	 * Android 4.0.4
	 * @return
	 */
	public static boolean hasIcecreamSandwichMR1(){
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1;
	}


	/**
	 * Android 4.1
	 * Android 4.1.1
	 * @return
	 */
	public static boolean hasJellyBean(){
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
	}


	/**
	 * Android 4.2
	 * Android 4.2.2
	 * @return
	 */
	public static boolean hasJellyBeanMR1(){
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
	}


	/**
	 * Android 4.3.x
	 * @return
	 */
	public static boolean hasJellyBeanMR2(){
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;
	}


	/**
	 * Android 4.4.x
	 * @return
	 */
	public static boolean hasKitkat(){
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
	}

	/**
	 * Android 5.0.1
	 * @return
	 */
	public static boolean hasLollipop(){
//		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
		return Build.VERSION.SDK_INT >= 21;
	}


	/**
	 * Android 5.1.1
	 * @return
	 */
	public static boolean hasLollipopMR1(){
//		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1;
		return Build.VERSION.SDK_INT >= 22;
	}


	/**
	 * Android 6.0
	 * @return
	 */
	public static boolean hasM(){
//		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
		return Build.VERSION.SDK_INT >= 23;
	}

}